<template>

  <div style="display: flex;justify-content: center;height: 100vh;align-items: center;flex-direction: column;">

    <div v-if="!gameStart" style="justify-content: center;align-items: center;cursor: pointer;display: flex;">
      <div @click="startGame"
           style="padding: 32px 72px;font-size: 32px;background-color: #fa7f7f;border-radius: 12px;color: #ffffff">开 始
      </div>
    </div>

    <div class="minesweeper">
      <div v-for="(row, rowIndex) in grid" :key="rowIndex" class="row">
        <div
            v-for="(cell, colIndex) in row"
            :key="colIndex"
            class="cell"
            @click="handleCellClick(rowIndex, colIndex)"
            :class="{ mine: cell.isMine, uncovered: cell.uncovered, flash: cell.flash }"
            :style="{ color: getCellTextColor(cell) }"
            @contextmenu.prevent="handleCellRightClick(cell)"
        >
          {{ getCellText(cell) }}
        </div>
      </div>
    </div>

    <div style="font-size: 24px;margin: 10px;display: flex;">
      <el-button @click="goHome">返回主页</el-button>
      <el-button @click="reStart" :disabled="!gameStart">重新开始</el-button>
    </div>

    <div style="position: absolute; top: 35vh;left: calc(50vw + 50vh - 25px);font-size: 24px;margin: 80px 0 0 10px;">
      <p>地雷数量: {{ NUM_MINES }}</p>
      <p>已插旗帜: {{ flagCount }}</p>
      <p>用时:{{ useTime }}秒</p>
    </div>

  </div>

</template>

<script setup lang="ts">
import {ref, onMounted} from 'vue';
import {messageSuccess} from "../../util/message.ts";
import {useRouter} from "vue-router";
import {uploadMineRecordRequest} from "../../api/mine_clear.ts";

const flagCount = ref(0);

const handleCellRightClick = (cell) => {
  if (gameOver.value){
    return
  }
  if (cell.uncovered) {
    if (!gameOver.value) {
      const surroundingCells = getSurroundingCells(cell);
      flashSurroundingCells(surroundingCells);
    }
  }else {
    cell.flag = !cell.flag;
    if (cell.flag){
      flagCount.value++;
    }else {
      flagCount.value--;
    }
  }
}

// 获取周围的单元格
const getSurroundingCells = (cell) => {
  const directions = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]];
  const surroundingCells = [];
  directions.forEach(([dx, dy]) => {
    const newRow = cell.row + dx;
    const newCol = cell.col + dy;
    if (newRow >= 0 && newRow < GRID_SIZE && newCol >= 0 && newCol < GRID_SIZE) {
      const surroundingCell = grid.value[newRow][newCol];
      if (!surroundingCell.uncovered) {
        surroundingCells.push(surroundingCell);
      }
    }
  });
  return surroundingCells;
}

// 闪烁周围的单元格
const flashSurroundingCells = (cells) => {
  cells.forEach(cell => {
    cell.flash = true;
  });
  // 3 秒后停止闪烁
  setTimeout(() => {
    cells.forEach(cell => {
      cell.flash = false;
    });
  }, 150);
}

const router = useRouter();

const goHome = () => {
  router.push("/user")
}

const reStart = () => {
  flagCount.value = 0;
  createGrid();
  plantMines();
  calculateAdjacentMines();
  startTime.value = Date.now();
  gameOver.value = false;
}

const GRID_SIZE = 30;
const NUM_MINES = 100;

// const GRID_SIZE = 10;
// const NUM_MINES = 1;

const grid = ref([]);

const getCellTextColor = (cell) => {
  if (cell.adjacentMines === 0) {
    return 'black';
  } else if (cell.adjacentMines === 1) {
    return 'blue';
  } else if (cell.adjacentMines === 2) {
    return 'green';
  } else if (cell.adjacentMines === 3) {
    return 'red';
  } else if (cell.adjacentMines === 4) {
    return 'brown';
  } else if (cell.adjacentMines === 5) {
    return 'purple';
  }
}

const getCellText = (cell) => {
  if (gameOver.value && cell.isMine){
    return '💣';
  }
  if (cell.uncovered) {
    if (cell.isMine) {
      return '💣';
    } else if (cell.adjacentMines > 0) {
      return cell.adjacentMines;
    } else {
      return '';
    }
  } else {
    if (cell.flag){
      return '🚩';
    }
    return '';
  }
}

const createGrid = () => {
  grid.value = [];

  for (let i = 0; i < GRID_SIZE; i++) {
    grid.value.push([]);
    for (let j = 0; j < GRID_SIZE; j++) {
      grid.value[i].push({
        isMine: false,
        uncovered: false,
        adjacentMines: 0,
        row: i,
        col: j,
        flash: false,
        flag: false
      });
    }
  }
};

const plantMines = () => {
  const positions = [];
  // 创建所有位置的数组
  for (let i = 0; i < GRID_SIZE; i++) {
    for (let j = 0; j < GRID_SIZE; j++) {
      positions.push([i, j]);
    }
  }
  // 随机洗牌数组
  for (let i = positions.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [positions[i], positions[j]] = [positions[j], positions[i]];
  }
  // 选取前 NUM_MINES 个位置放置地雷
  for (let i = 0; i < NUM_MINES; i++) {
    const [row, col] = positions[i];
    grid.value[row][col].isMine = true;
  }
};

// 计算每个格子周围的雷数量
const calculateAdjacentMines = () => {
  const directions = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]];
  for (let i = 0; i < GRID_SIZE; i++) {
    for (let j = 0; j < GRID_SIZE; j++) {
      if (!grid.value[i][j].isMine) {
        let count = 0;
        directions.forEach(([dx, dy]) => {
          const newRow = i + dx;
          const newCol = j + dy;
          if (newRow >= 0 && newRow < GRID_SIZE && newCol >= 0 && newCol < GRID_SIZE && grid.value[newRow][newCol].isMine) {
            count++;
          }
        });
        grid.value[i][j].adjacentMines = count;
      }
    }
  }
};

const onClickMine = () => {
  gameOver.value = true;
}

const handleCellClick = (rowIndex, colIndex) => {
  if (gameOver.value) {
    return;
  }

  lastClickTime.value = Date.now();

  const handleCellClickInner = (rowIndex, colIndex) => {
    const cell = grid.value[rowIndex][colIndex];
    if (cell.flag){
      return
    }
    if (!cell.uncovered) {
      cell.uncovered = true;
      if (cell.isMine) {
        onClickMine();
      } else if (cell.adjacentMines === 0) {
        const directions = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]];
        directions.forEach(([dx, dy]) => {
          const newRow = rowIndex + dx;
          const newCol = colIndex + dy;
          if (newRow >= 0 && newRow < GRID_SIZE && newCol >= 0 && newCol < GRID_SIZE) {
            handleCellClickInner(newRow, newCol);
          }
        });
      }
    }
  }
  handleCellClickInner(rowIndex, colIndex);
  // Check if all non-mine cells are uncovered
  const allCellsUncovered = grid.value.every((row) => row.every((cell) => cell.uncovered || cell.isMine));
  if (allCellsUncovered) {
    // 游戏结束
    gameOver.value = true;
    const intTime = lastClickTime.value - startTime.value;
    useTime.value = (intTime / 1000).toFixed(3);
    messageSuccess("恭喜你，成功完成游戏！");
    uploadMineRecordRequest(intTime).then((response)=>{
      if (response.success){
        messageSuccess("记录上传成功！");
      }
    })
  }
};

const gameStart = ref(false);
const gameOver = ref(false);

const startTime = ref(-1)
const useTime = ref("0")
const lastClickTime = ref(-1)

function secondCount() {
  if (gameStart.value && !gameOver.value) {
    useTime.value = ((Date.now() - startTime.value) / 1000).toFixed(3);
  }
  requestAnimationFrame(secondCount);
}

requestAnimationFrame(secondCount);

const startGame = () => {
  createGrid();
  plantMines();
  calculateAdjacentMines();
  gameStart.value = true;
  startTime.value = Date.now();
}

onMounted(() => {

});
</script>

<style scoped>
.minesweeper {
  display: flex;
  flex-direction: column;
  border: 2px solid #ccc;
  border-right-width: 0;
  border-bottom-width: 0;
}

.row {
  display: flex;
}

.cell {
  width: 20px;
  height: 20px;
  border: 2px solid #ccc;
  border-top-width: 0;
  border-left-width: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.mine {

}

.uncovered {
  background-color: #eee;
}

.uncovered.mine{
  background-color: red;
}

.flash{
  background-color: yellow;
}

</style>
